﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Ivony.Html;
using Ivony.Html.Parser;
using WebKit;

namespace WindowsFormsApp1
{
	public partial class huitu : Form
	{
		WebKitBrowser browser = null;
		public huitu()
		{
			InitializeComponent();
			browser = new WebKitBrowser();
			browser.Dock = DockStyle.Fill;
			this.Controls.Add(browser);
			this.browser.NewWindowCreated += new WebKit.NewWindowCreatedEventHandler(this.webKitBrowser1_NewWindowCreated);

		}
		/// <summary>
		/// webbrower浏览器挂起
		/// </summary>
		/// <param name="Millisecond"></param>
		private void Delay(int Millisecond)
		{
			DateTime current = DateTime.Now;
			while (current.AddMilliseconds(Millisecond) > DateTime.Now)
			{
				Application.DoEvents();
			}
			return;
		}
		private void button1_Click(object sender, EventArgs e)
		{

			try
			{


				browser.Navigate("http://www.huitu.com/design");
				//while (true)
				//{
				//	Delay(50);//延迟50毫秒b'h
				//	if (browser.== WebBrowserReadyState.Complete)//判断文档是否加载完毕
				//	{
				//		if (!browser.IsBusy)
				//		{
				//			break;
				//		}
				//	}
				//	continue;
				//}
				browser.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.webBrowser1_DocumentCompleted);
				/*	var request = (HttpWebRequest)WebRequest.Create("http://www.huitu.com/design");
					var response = (HttpWebResponse)request.GetResponse();
					var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
					dateHtml(responseString);*/

			}
			catch (Exception ec)
			{

			}
		}


		private JumonyParser jp = new JumonyParser();

		public void dateHtml(string html)
		{ 
			string c1 = "";

			var dataDocument = jp.Parse(html);
			//var mumberlist = dataDocument.Find("#naviLitemDesign").ToArray();

			string[] aa = new string[] { "http://www.huitu.com/design/26/", "http://www.huitu.com/design/31/", "http://www.huitu.com/design/38/", "http://www.huitu.com/design/30/", "http://www.huitu.com/design/27/" , "http://www.huitu.com/design/32/", "http://www.huitu.com/design/29/", "http://www.huitu.com/design/33/", "http://www.huitu.com/design/36/", "http://www.huitu.com/design/37/", "http://www.huitu.com/design/28/" , "http://www.huitu.com/design/34/", "http://www.huitu.com/design/44/", "http://www.huitu.com/design/49/" };

			for (int i = 0; i < aa.Length; i++)
			{
				for (int j = 1; j < 5000; j++)
				{
					string ur = aa[i] + j + ".html";
					var request = (HttpWebRequest)WebRequest.Create(ur);
					var response = (HttpWebResponse)request.GetResponse();
					var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
					if (string.IsNullOrWhiteSpace(responseString))
					{
						break;
					}
					else
					{
						dateHtml1(responseString);
					}
				}

				 
			}
		}

		public void dateHtml1(string html)
		{  
			var dataDocument = jp.Parse(html);
			var c1 = "";
			var alllist = dataDocument.Find(".main-pic li").ToArray();
			for (int i = 0; i < alllist.Length; i++)
			{
				var alink = alllist[i].Find("a").ToArray();
				if (alink.Length > 0)
				{
					c1 = alink[0].Attribute("href").Value();//获取名字  

					var request = (HttpWebRequest)WebRequest.Create(c1);
					var response = (HttpWebResponse)request.GetResponse();
					var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
					dateHtml2(responseString);
					
				}
			}
		}


		private void webKitBrowser1_NewWindowCreated(object sender, WebKit.NewWindowCreatedEventArgs e)
		{
			
			//初始化窗口
			e.WebKitBrowser.Navigating += new WebBrowserNavigatingEventHandler(WebKitBrowser_Navigating);
			e.WebKitBrowser.Location = new Point(2000, 2000);
			this.Controls.Add(e.WebKitBrowser);
		}
		void WebKitBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
		{
			//WebKitBrowser弹出的新链接地址
			string url = e.Url.ToString();
		}


		private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
		{
			
			var xmlStr = browser.DocumentText;
			dateHtml(xmlStr);
		}

		public void dateHtml2(string html)
		{
			//http://www.huitu.com/design/31/5250.html
			string savepath = @"D:\sjImg";
			var name = "";
			var dataDocument = jp.Parse(html);
			var cishu = dataDocument.Find("#downloadnumI").ToArray();
			var cishu1= int.Parse(cishu[0].ToString());
			if (cishu1 > 0)
			{
				var title = dataDocument.Find(".picname-tit").ToArray();
				var c1name = title[0].Attribute("title").Value();//获取名字   

				var imgsa = dataDocument.Find(".bigimg").ToArray();
				foreach (var img in imgsa)
				{
					var src = img.Attribute("src").Value();
					name = img.Attribute("alt").Value();
					if (!string.IsNullOrWhiteSpace(name))
					{
						DownloadImage(src, savepath + "\\sheji\\", cishu1 + c1name + src + ".jpg");
					}

				}

			}
		}
			/// 网络地址
			/// 本地保存路径
			public static string DownloadImage(string url, string path, string name)
		{
			HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
			req.ServicePoint.Expect100Continue = false;
			req.Method = "GET";
			req.KeepAlive = true;
			req.ContentType = "image/*";
			HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
			System.IO.Stream stream = null;
			int i = url.LastIndexOf(".");
			string StrType = url.Substring(i);
			//string filename = Guid.NewGuid().ToString();
			try
			{
				CreateDirectory(path);
				// 以字符流的方式读取HTTP响应
				stream = rsp.GetResponseStream();
				Image.FromStream(stream).Save(path + "\\" + name.Replace(@"\", "").Replace(@"/", "") + StrType);
			}
			catch
			{

			}
			finally
			{
				// 释放资源
				if (stream != null) stream.Close();
				if (rsp != null) rsp.Close();
			}
			return name + StrType;
		}


		/// 网络地址
		/// 本地保存路径
		public static string DownloadImages(string url, string path, string name)
		{
			HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
			req.ServicePoint.Expect100Continue = false;
			req.Method = "GET";
			req.KeepAlive = true;
			req.ContentType = "image/*";
			HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
			System.IO.Stream stream = null;
			int i = url.LastIndexOf(".");
			string StrType = url.Substring(i);
			string filename = Guid.NewGuid().ToString();
			try
			{
				CreateDirectory(path);
				// 以字符流的方式读取HTTP响应
				stream = rsp.GetResponseStream();
				Image.FromStream(stream).Save(path + "\\" + name);
			}
			finally
			{
				// 释放资源
				if (stream != null) stream.Close();
				if (rsp != null) rsp.Close();
			}
			return filename + StrType;
		}


		#region 创建一个目录  
		/// <summary>  
		/// 创建一个目录  
		/// </summary>  
		/// <param name="directoryPath">目录的绝对路径</param>  
		public static void CreateDirectory(string directoryPath)
		{
			//如果目录不存在则创建该目录  
			if (!IsExistDirectory(directoryPath))
			{
				Directory.CreateDirectory(directoryPath);
			}
		}
		#endregion

		#region 检测指定目录是否存在  
		/// <summary>  
		/// 检测指定目录是否存在  
		/// </summary>  
		/// <param name="directoryPath">目录的绝对路径</param>          
		public static bool IsExistDirectory(string directoryPath)
		{
			return Directory.Exists(directoryPath);
		}
		#endregion

		private void button2_Click(object sender, EventArgs e)
		{

		}
	}
}
